package io.renren.modules.front.base;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;


/**
 * <p>
 * 前端功能的BaseController
 * </p>
 *
 * @author yuxiaobin
 * @date 2017/8/21
 */
public abstract class FrontBaseController {

    protected final org.slf4j.Logger logger = LoggerFactory.getLogger(this.getClass().getName().substring(this.getClass().getName().lastIndexOf(".")));
    public static final String MSG = "msg";//成功消息
    public static final String VERROR = "verror";//验证错误消息
    public static final String RELOAD = "reload";//是否重新加载图片验证码

    protected static final String SESSION_NAME_FOR_USER = "loginUser";

    @Autowired(required=false)
    protected HttpServletRequest request;
    @Autowired(required=false)
    protected HttpServletResponse response;

    public ResponseEntity<JSON> getSuccessResult(JSON result){
        return new ResponseEntity<JSON>(result, HttpStatus.OK);
    }

    public ResponseEntity<JSON> getInvalidParamResult(JSON result){
        return new ResponseEntity<JSON>(result, HttpStatus.BAD_REQUEST);
    }

    public ResponseEntity<JSON> getInvalidParamResult(){
        return new ResponseEntity<JSON>(new JSONObject(1), HttpStatus.BAD_REQUEST);
    }

    public ResponseEntity<JSON> getNoRecordFoundResult(JSON result){
        return new ResponseEntity<JSON>(result, HttpStatus.NO_CONTENT);
    }

    public ResponseEntity<JSON> getInternalServerResult(JSON result){
        return new ResponseEntity<JSON>(result, HttpStatus.INTERNAL_SERVER_ERROR);
    }

    public boolean checkLogined(){
        return request!=null && request.getSession().getAttribute(SESSION_NAME_FOR_USER)!=null;
    }

    public String getSourceIpAddr() {
        String ip = request.getHeader("x-forwarded-for");
        if (isEmptyStr(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (isEmptyStr(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (isEmptyStr(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        if (isNotEmptyStr(ip)) {
            ip = ip.split(",")[0];
        }
        return ip;
    }

    public boolean isEmptyStr(String str){
        return str==null || str.trim().isEmpty();
    }

    public boolean isNotEmptyStr(String str){
        return !isEmptyStr(str);
    }
}
